package models

import (
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	_ "github.com/go-sql-driver/mysql"
	"net/url"
)

func Init() {
	dbhost := beego.AppConfig.String("db.host")
	dbport := beego.AppConfig.String("db.port")
	dbuser := beego.AppConfig.String("db.user")
	dbpassword := beego.AppConfig.String("db.password")
	dbname := beego.AppConfig.String("db.name")
	timezone := beego.AppConfig.String("db.timezone")
	if dbport == "" {
		dbport = "3306"
	}
	dsn := dbuser + ":" + dbpassword + "@tcp(" + dbhost + ":" + dbport + ")/" + dbname + "?charset=utf8"
	if timezone != "" {
		dsn = dsn + "&loc=" + url.QueryEscape(timezone)
	}
	//fmt.Printf("输出连接信息：%s", dsn)
	orm.RegisterDataBase("default", "mysql", dsn)
	orm.RegisterModel(new(Article), new(Category), new(Admin))

	if beego.AppConfig.String("runmode") == "dev" {
		orm.Debug = true
	}
}

func TableName(name string) string {
	return beego.AppConfig.String("db.prefix") + name
}

func ApiGetList(modelObj interface{}, page int, limit int, filters ...interface{}) (interface{}, int64) {

	offset := (page - 1) * limit
	o := orm.NewOrm()
	qs := o.QueryTable(modelObj) // 返回 QuerySeter
	if len(filters) > 0 {
		l := len(filters)
		for k := 0; k < l; k += 2 {
			qs = qs.Filter(filters[k].(string), filters[k+1])
		}
	}
	total, _ := qs.Count()
	list := make(map[string]interface{})
	qs.OrderBy("-created_at").Limit(limit, offset).All(&list)
	return list, total
}
